package org.xelnaga.defiler.web.controller.login;


import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xelnaga.defiler.domain.UserModel;
import org.xelnaga.defiler.security.SpringSecurityContext;

/**
 * The login controller checks if any login error is present in the Spring Security context.
 * <p>
 * When an error is present, the LoginController rejects the value using the BindingResult facility. This way, the error message is available from the view as
 * any other error message. Bear in mind that this controller is invoked only to display the login page and in case of authentication failure.
 * <p>
 * The login phase itself is done by SpringSecurity.
 * <p>
 * Note: This controller name is forced only to minimize the risks of name collisions. It is not used since controllers sit on top of everything else.
 */
@Controller("loginControllerExample")
@RequestMapping("/login")
public class LoginController {

	private List<String> grantedRoles = new UserModel().getRoleNames();

	@RequestMapping( { "/index", "/", ""})
    public String index(@ModelAttribute LoginForm loginForm, BindingResult result, HttpServletRequest request) {
        AuthenticationException ae = (AuthenticationException) request.getSession().getAttribute(
        		WebAttributes.AUTHENTICATION_EXCEPTION);
        if (ae != null) {
            result.reject("login.unsuccessful");
        } else {
        	if(StringUtils.isNotBlank(SpringSecurityContext.getUsername()) 
        			&& !StringUtils.equalsIgnoreCase("anonymousUser", SpringSecurityContext.getUsername())) {
        		return "/user/index";
        	}
        }
        return "/login/index";
    }
    
    @RequestMapping( { "/checkLogin"})
    public String checkLogin(@ModelAttribute LoginForm loginForm, BindingResult result, HttpServletRequest request) {
    	SpringSecurityContext.forceAuthentication(loginForm.getJ_username(), loginForm.getJ_password(), grantedRoles);
    	
    	if(StringUtils.isNotBlank(SpringSecurityContext.getAuthencatedUsername())) {
    		return "redirect:/auction/checkOut";
    	} else {
    		return "redirect:/auction/checkOut";
    	}
    }
}